package com.xiaochong.tir.manager.controller;

import com.github.pagehelper.PageInfo;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.service.common.config.oss.OSSTool;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.data.po.*;
import com.xiaochong.tir.common.data.vo.serchReportGradeVo;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import com.xiaochong.tir.manager.service.SyResearchReportFileService;
import com.xiaochong.tir.manager.service.SyResearchReportOrLabelService;
import com.xiaochong.tir.manager.service.SyResearchReportService;
import com.xiaochong.tir.manager.util.ManagerVersion;
import com.xiaochong.tir.common.data.vo.ResearchReportListVo;
import com.xiaochong.tir.manager.util.ReturnResult;
import com.xiaochong.tir.manager.util.SessionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.*;

/**
 * Created by admin on 2018/4/28.
 */
@Controller
@Api("研报列表")
@RequestMapping(value = ManagerVersion.API_V1_PREFIX+"research/")
public class ResearchReportController {

    @Autowired
    private SyResearchReportFileService syResearchReportFileService;
    @Autowired
    private SyResearchReportOrLabelService syResearchReportOrLabelService;
    @Autowired
    private SyResearchReportService syResearchReportService;
	@Autowired
	private OSSTool ossTool;
	@Autowired
	private RedisServer redisServer;
	/**
	 * 删除研报
	 * @param researchId
	 * @return
	 */
    @ApiOperation(value = "删除研报",notes = "删除研报")
    @PostMapping("delelteReport")
    @ResponseBody
	public Object delelteReport(@RequestParam("researchId") Integer researchId) {
		redisServer.set(RedisKeysUtils.LOGINNAME,"删除研报");
		try {
			SyResearchReportFile srf = new SyResearchReportFile();
			SyResearchReportOrLabel srrl = new SyResearchReportOrLabel();
			// 删除研报表记录
			SyResearchReport syResearchReport = new SyResearchReport();
			SyResearchReport old =syResearchReportService.selectByPrimaryKey(researchId);
			syResearchReport.setId(researchId);
			syResearchReport.setDeleteFlag(true);
			syResearchReport.setEnableFlag(old.getEnableFlag());
			syResearchReport.setUpdateTime(new Date());
			syResearchReportService.updateByPrimaryKey(syResearchReport,old);
			// 删除图片表记录
			srf.setResearchReportId(researchId);
			syResearchReportFileService.deleteBatch(srf);
			// 删除研报、标签中间表记录
			srrl.setResearchReportId(researchId);
			syResearchReportOrLabelService.deleteBatch(srrl);
		} catch (Exception e) {
			e.printStackTrace();
			LogTrace.error(getClass().getSimpleName() + "/delelteReport", e.getLocalizedMessage(), e);
			return new ReturnResult<SyResearchReport>(-1, "删除失败", 0, 0);
		}
		return new ReturnResult<SyResearchReport>(1, "删除成功！", 1, 0);
	}

	/**
	 * 研报列表
	 * @param vo
	 * @return
	 */
    @ApiOperation(value = "查询研报列表",notes = "查询研报列表")
    @PostMapping(value = "serchReportList")
    @ResponseBody
    public Object serchReportList(ResearchReportListVo vo){
        PageInfo<serchReportGradeVo> list = syResearchReportService.serchReportList(vo);
        ReturnResult<serchReportGradeVo> result = new ReturnResult<serchReportGradeVo>(0,"成功",list.getList(),list.getTotal());
        return result;
    }

	/**
	 * 研报上/下架
	 * @param id
	 * @param enableFlag
	 * @return
	 */
    @ApiOperation(value = "研报上/下架",notes = "研报上/下架")
    @PostMapping(value = "enableReport")
    @ResponseBody
    public int enableReport(@RequestParam("id")Integer id,@RequestParam("enableFlag")Boolean enableFlag){
		redisServer.set(RedisKeysUtils.LOGINNAME,"研报上/下架");
        SyResearchReport srr = new SyResearchReport();
        srr.setId(id);
        if(enableFlag .equals(true) ){
            srr.setEnableFlag(false);
        }else {
            srr.setEnableFlag(true);
        }
        srr.setUpdateTime(new Date());
       int count = syResearchReportService.updateByPrimaryKey(srr,syResearchReportService.selectByPrimaryKey(id));
       return count;
    }

	/**
	 * 发布研报
	 * @param syResearchReport
	 * @param filePath
	 * @param labelList
	 * @param webImgUrl
	 * @return
	 */
    @ApiOperation(value = "发布研报",notes = "发布研报")
    @PostMapping(value = "saveResearchReport")
    @ResponseBody
    public Object saveResearchReport(SyResearchReport syResearchReport,
                         @RequestParam(value = "filePath",required = false)String filePath,
                         @RequestParam(value = "labelList",required = false)String labelList,
                         @RequestParam(value = "webImgUrl",required = false)String webImgUrl,
						 @RequestParam(value = "appImgUrl",required = false)String appImgUrl) {
		redisServer.set(RedisKeysUtils.LOGINNAME,"发布研报");
		try {
			SyResearchReport report = syResearchReportService.selectByEntity(syResearchReport);
			if(null != report){
				return new ReturnResult<SyResearchReport>(-1, "重复添加！", 1, 0);
			}
			// 添加研报表记录
			if (syResearchReport.getSendType().equals(0)) {
				syResearchReport.setTimingTime(new Date());
			}
			syResearchReport.setCreateTime(new Date());
			syResearchReport.setUpdateTime(new Date());
			syResearchReport.setEnableFlag(true);
			syResearchReport.setDeleteFlag(false);
			syResearchReportService.insertSelective(syResearchReport);
			int id = syResearchReport.getId();// (返回新增的id)
			// 保存文档&封面图
			String[] publishPlatforms = syResearchReport.getPublishPlatform().split(";");
			SyResearchReportFile srf = new SyResearchReportFile();
			srf.setResearchReportId(id);
			srf.setDeleteFlag(false);// 是否删除
			srf.setCreateTime(new Date());// 创建时间
			srf.setUpdateTime(new Date());
			srf.setSort(id);
			for (int i = 0; i < publishPlatforms.length; i++) {
				srf.setPublishPlatform(publishPlatforms[i]);
				if (StringUtils.isNotBlank(filePath)) {
					srf.setFileName(filePath);
					srf.setType(1);
					syResearchReportFileService.insertSelective(srf);
				}
				if(publishPlatforms[i].equals("1")){
					srf.setFileName(webImgUrl);
					srf.setFilePath(webImgUrl);
				}else if(publishPlatforms[i].equals("2")){
					srf.setFileName(appImgUrl);
					srf.setFilePath(appImgUrl);
				}
				srf.setType(0);
				syResearchReportFileService.insertSelective(srf);
			}

			// 添加标签
			if (!"".equals(labelList)) {
				String[] labelLists = labelList.split(";");
				for (int i = 0; i < labelLists.length; i++) {
					SyResearchReportOrLabel srrl = new SyResearchReportOrLabel();
					srrl.setResearchReportId(id);
					srrl.setEnableFlag(true);
					srrl.setDeleteFlag(false);
					srrl.setCreateTime(new Date());
					srrl.setUpdateTime(new Date());
					srrl.setLabelId(Integer.parseInt(labelLists[i]));
					syResearchReportOrLabelService.insertSelective(srrl);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogTrace.error(getClass().getSimpleName() + "/saveResearchReport", e.getMessage(), e);
			return new ReturnResult<SyResearchReport>(-1, "新增失败", 0, 0);
		}
		return new ReturnResult<SyResearchReport>(1, "新增成功！", 1, 0);
	}

	/**
	 * 修改研报
	 * @param syResearchReport
	 * @param filePath
	 * @param labelList
	 * @param webImgUrl
	 * @param appImgUrl
	 * @return
	 */
    @ApiOperation(value = "修改研报", notes = "修改研报" )
    @PostMapping(value = "updateResearchReport")
    @ResponseBody
    public Object updateResearchReport(SyResearchReport syResearchReport,
            @RequestParam(value = "filePath",required = false)String filePath,
            @RequestParam(value = "labelList",required = false)String labelList,
			@RequestParam(value = "webImgUrl", required = false) String webImgUrl,
			@RequestParam(value = "appImgUrl",required = false)String appImgUrl) {
		redisServer.set(RedisKeysUtils.LOGINNAME,"修改研报");
		try {
			// 保存文档
			SyResearchReportFile srf = new SyResearchReportFile();
			//封面图
			String[] publishPlatforms = syResearchReport.getPublishPlatform().split(";");
			srf.setSort(syResearchReport.getId());
			srf.setResearchReportId(syResearchReport.getId());
			srf.setCreateTime(new Date());// 创建时间
			srf.setUpdateTime(new Date());
			srf.setDeleteFlag(false);// 是否删除
			for (int i = 0; i < publishPlatforms.length; i++) {
				srf.setPublishPlatform(publishPlatforms[i]);
				if (StringUtils.isNotBlank(filePath)) {
					srf.setType(1);
					syResearchReportFileService.deleteByResearchReportId(srf);
					srf.setFileName(filePath);
					srf.setFilePath(ossTool.getOSSUrl(filePath));
					syResearchReportFileService.insertSelective(srf);
					filePath ="";
				}
				srf.setType(0);
				if(publishPlatforms[i].equals("1")){
					syResearchReportFileService.deleteByResearchReportId(srf);
					srf.setFileName(webImgUrl);
					srf.setFilePath(ossTool.getOSSUrl(webImgUrl));
					syResearchReportFileService.insertSelective(srf);
				}
				if(publishPlatforms[i].equals("2")){
					syResearchReportFileService.deleteByResearchReportId(srf);
					srf.setFileName(appImgUrl);
					srf.setFilePath(ossTool.getOSSUrl(appImgUrl));
					syResearchReportFileService.insertSelective(srf);
				}
			}

			// 添加标签
			if (StringUtils.isNotBlank(labelList)) {
				syResearchReportOrLabelService.deleteByResearchReportId(syResearchReport.getId());
				String[] labelLists = labelList.split(";");
				for (int i = 0; i < labelLists.length; i++) {
					SyResearchReportOrLabel srrl = new SyResearchReportOrLabel();
					srrl.setResearchReportId(syResearchReport.getId());
					srrl.setEnableFlag(true);
					srrl.setDeleteFlag(false);
					srrl.setCreateTime(new Date());
					srrl.setUpdateTime(new Date());
					srrl.setLabelId(Integer.parseInt(labelLists[i]));
					syResearchReportOrLabelService.insertSelective(srrl);
				}
			}

			// 修改研报表记录
			syResearchReport.setUpdateTime(new Date());
			SyResearchReport old = syResearchReportService.selectByPrimaryKey(syResearchReport.getId());
			syResearchReport.setEnableFlag(old.getEnableFlag());
			syResearchReportService.updateByPrimaryKey(syResearchReport,old);
		} catch (Exception e) {
			e.printStackTrace();
			LogTrace.error(getClass().getSimpleName() + "/updateResearchReport", e.getMessage(), e);
			return new ReturnResult<SyResearchReport>(-1, "保存失败", 0, 0);
		}
		return new ReturnResult<SyResearchReport>(1, "保存成功！", 1, 0);
	}

	/**
	 * 查询频道（下拉框）
	 * @return
	 */
	@ApiOperation(value = "查询频道列表",notes = "查询频道列表")
    @GetMapping("selchannlList")
    @ResponseBody
    public List<SyChannels> selchannlList(){
        List<SyChannels> list = syResearchReportService.ChannlList();
        return list;
    }

	/**
	 *  查询标签（复选框）
	 * @return
	 */
	@ApiOperation(value = "查询频道列表", notes = "查询频道列表")
	@GetMapping("sellabelList")
	@ResponseBody
	public List<SyLabel> labelList() {
		List<SyLabel> list = syResearchReportService.labelList();
		return list;
	}

	/**
	 * 研报列表页面
	 * @return
	 */
	@RequestMapping(value = "researchReportList", method = RequestMethod.GET)
	public String researchReportList() {
		return "/research/researchReportList";
	}

	/**
	 * 新增研报页面
	 * @return
	 */
	@RequestMapping(value = "researchReportAdd", method = RequestMethod.GET)
	public String researchReportAdd() {
		return "/research/researchReportAdd";
	}

	/**
	 *  修改研报页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "researchReportEdit", method = RequestMethod.GET)
	public String researchReportEdit(@RequestParam("id") Integer id, Model model) {
		SyResearchReport syResearchReport = syResearchReportService.selectByPrimaryKey(id);
		model.addAttribute("data", syResearchReport);
		List<SyLabel> list = syResearchReportService.labelList();
		List<SyResearchReportOrLabel> labelList = syResearchReportOrLabelService.getLabelByReportId(id);
		for (SyLabel syLabel : list) {
			for (SyResearchReportOrLabel rlable : labelList) {
				if ((syLabel.getId() + "").equals(rlable.getLabelId() + "")) {
					syLabel.setIsChecked(1);
				}
			}
		}
		model.addAttribute("list", list);
		// 查询封面和文件
		List<SyResearchReportFile> imgList = syResearchReportFileService.getResearchReportImage(id);
		if(null != imgList){
			for (int i = 0; i < imgList.size(); i++) {
				SyResearchReportFile image = imgList.get(i);
				if(StringUtils.isNotBlank(image.getFileName()) && !image.getFileName().contains("http")){
					image.setFilePath(ossTool.getOSSUrl(image.getFileName()));
				}
			}
		}
		model.addAttribute("image", imgList == null ? new SyResearchReportFile() : imgList);
		return "/research/researchReportEdit";
	}

	/**
	 * 研报置顶
	 * @param id
	 * @param setTop
	 * @return
	 */
	@ApiOperation(value = "研报置顶",notes = "研报置顶")
	@PostMapping("researchSetTop")
	@ResponseBody
	public Object researchSetTop(@RequestParam(value = "id")Integer id,
								 @RequestParam(value = "setTop",required = false) Boolean setTop){
		redisServer.set(RedisKeysUtils.LOGINNAME,"研报置顶");
		SyResearchReport report = new SyResearchReport();
		SyResearchReport old = syResearchReportService.selectByPrimaryKey(id);
		if(null!=setTop && setTop){
			report.setSetTop(false);
		}else{
			report.setSetTop(true);
		}
		report.setId(id);
		report.setUpdateTime(new Date());
		report.setEnableFlag(old.getEnableFlag());
		report.setDeleteFlag(old.getDeleteFlag());
		syResearchReportService.updateByPrimaryKey(report,old);
		return new ReturnResult<>(0,"成功",1,1);
	}
    
}


